/**
 * Login页面
 * 
 * @author Gill Gong
 */

import React from 'react'
import { 
  ImageBackground,
  SafeAreaView, 
  StyleSheet, 
  TextInput, 
  Button, 
  Alert,
  View, 
  Text
} from 'react-native'

import config from '~/config'
import store from '~/common/store'
import Mask from "~/components/mask"
import modelFactory from '~/models/factory'
//import console = require('console');

let loginModel = modelFactory.createForm({
  method: 'Post',
  url: `${config.gateway}/authentification-service/authentification/login`
})

const STATUS = {
  LOADING: 'loading',
  EDIT: 'edit'
}

class Login extends React.Component {
  static navigationOptions = () => {
    
    return {
      header: null
    }
  }

  constructor(ops) {
    super(ops)

    this.state = {
      userName: '',
      password: '',
      status: STATUS.EDIT
    }
  }

  render() {

    return (
      <SafeAreaView style={{ flex: 1, height: "100%" }}>
        { this.renderEdit() }
        {
          this.state.status === STATUS.LOADING && this.renderLoading()
        }
      </SafeAreaView>
    )
  }

  renderLoading() {

    return (
      <Mask>
        <Text style={{ fontSize: 50, color: "#fff", fontWeight: "bold" }}>Login...</Text>
      </Mask>
    )
  }

  renderEdit() {

    return (
      <View>
        <View style={{ alignItems: "center", justifyContent: "center", marginBottom: 20 }}>
          <ImageBackground style={{ width: '100%', height: 180 }} source={ require('~/assets/imgs/hot-rewer.jpg') }>
            <Text style={{ 
              fontSize: 40, 
              color: '#fff',
              paddingTop: 10, 
              textAlign:"center"
            }}>
            Welcome to login 
            </Text>
          </ImageBackground>
        </View>
        <View style={[ styles.inputRow ]}>
          <Text style={{ fontSize: 18 }}>用户名</Text>
          <TextInput
          placeholder="电话、邮件、账号"
          style={[ styles.inputText ]} value={ this.state.userName }
          onChangeText={text => this.onUserNameChange(text)}>
          </TextInput>
        </View>
        <View style={[ styles.inputRow ]}>
          <Text style={{ fontSize: 18 }}>密码</Text>
          <TextInput
          autoCompleteType="password"
          placeholder="数字、字母、下划线"
          style={[ styles.inputText ]} value={ this.state.password }
          onChangeText={text => this.onPasswordChange(text)}></TextInput>
        </View>
        <View style={{ padding: 50 }}>
          <Button title="Login" onPress={ () => this.login() } />
        </View>
      </View>
    )
  }

  login() {
    let {
      userName: account,
      password
    } = this.state

    if(this.validate()) {
      this.setState({ status: STATUS.LOADING }, function() {
      
        loginModel.exec({
          account,
          password
        }).then((token)=>{
      
          store.setToken(token).then(()=>{

            this.setState({ status: STATUS.EDIT })
            this.props.onLoginedSuccessHandler()
          })
        }).catch((error)=>{
    
          this.setState({ status: STATUS.EDIT })
          Alert.alert(
            'Error',
            error.message,
            [{ text: '确认', onPress: ()=>{} }]
          )
        })
      })
    }
  }

  validate(){
    let {
      userName,
      password
    } = this.state
    let showWarning = function(message) {
      
      Alert.alert(
        'Warning',
        message,
        [{ text: '确认', onPress: ()=>{} }]
      )

      return false
    }

    if(_.isEmpty(userName)) {
      return showWarning('用户名不许为空')
    }

    if(_.isEmpty(password)) {
      return showWarning('密码不许为空')
    }

    return true
  }

  onUserNameChange(newUserName) {

    this.setState({ userName: newUserName })
  }

  onPasswordChange(newPassword) {

    this.setState({ password: newPassword })
  }
}

const styles = StyleSheet.create({
  inputRow: {
    paddingTop: 10,
    paddingBottom: 10,
    paddingLeft: 30,
    paddingRight: 30
  }, 
  inputText: {
    marginTop: 10,
    height: 40,
    borderBottomWidth: 1,
    borderBottomColor: "#666",
  },
  image: {
    width: 100,
    height: 40,
    marginLeft: 20
  }
})

export default Login